package me.sdau.spider.openapi.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import me.sdau.spider.openapi.entity.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.Optional;

import static me.sdau.spider.openapi.comm.Const.HEADER_STRING;
import static me.sdau.spider.openapi.comm.Const.TOKEN_PREFIX;


@Slf4j
@Service
public class TokenAuthenticationService {
    //    private final long EXPIRATIONTIME = 1000*60*60*24*1; // 1 days
    private final long EXPIRATIONTIME = 1000 * 60 * 30; // 30 mins
    private final String SECRET = "ThisIsASecret";

    public String create(User user) {
        return Jwts.builder()
                .setSubject(user.getAccount())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                .claim("api", user.getApi())
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    public Optional<Authentication> getAuthentication(HttpServletRequest request) throws JwtException {
        String token = request.getHeader(HEADER_STRING);
        if (token != null && !token.isEmpty()) {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();

            return Optional.of(new UsernamePasswordAuthenticationToken(claims, null, Collections.emptyList()));
        }
        return Optional.empty();
    }

}
